import { StringUtils } from "@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/utils/StringUtils.ts"

/**
 * 打开数据库
 * @param {string} dbName 数据库名
 * @param {string} dbPath 数据库地址
 * @return 
 */ 
export function openSqlite(dbName : string, dbPath ?: string) : Promise<string> {
	return new Promise((resolve, reject) => {
		if (StringUtils.isEmpty(dbPath)) {
			// 获取应用的私有存储目录
			const dir = plus.io.convertLocalFileSystemURL('_doc');
			// 拼接数据库文件名，这里假设数据库名为 app.db
			dbPath = `${dir}${dbName}.db`;
		}
		const isOpen = plus.sqlite.isOpenDatabase({
			name: dbName,
			path: dbPath
		});
		if (isOpen) {
			console.log('isopen-----')
			return dbPath!;
		}
		plus.sqlite.openDatabase({
			name: dbName,
			path: dbPath,
			success: () => {
				console.log('打开成功')
				resolve(dbPath!);
			},
			fail: (error) => {
				console.error(`打开数据库${dbName}(${dbPath})失败！`,error)
				reject(error);
			}
		});
		console.debug(`打开数据库${dbName}(${dbPath})成功`);
	});
}

/**
 * 关闭数据库
 * @param {string} dbName 数据库名
 * @param {string} dbPath 数据库地址
 * @return 
 */ 
export function closeSqlite(dbName : string, dbPath ?: string) : Promise<void> {
	return new Promise((resolve, reject) => {
		if (StringUtils.isEmpty(dbPath)) {
			// 获取应用的私有存储目录
			const dir = plus.io.convertLocalFileSystemURL('_doc');
			// 拼接数据库文件名，这里假设数据库名为 app.db
			dbPath = `${dir}app.db`;
		}
		plus.sqlite.closeDatabase({
			name: dbName,
			success: () => {
				resolve();
			},
			fail: (error) => {
				console.error(`关闭数据库${dbName}(${dbPath})失败！`,error)
				reject(error);
			}
		});
	});
}

/**
 * 增删改语句
 * @param {string} dbName 数据库名
 * @param {string} sql 
 * @return 
 */ 
export function executeSql(dbName : string, sql: string | string[]) : Promise<boolean> {
	console.error("executeSql：", sql);
	return new Promise((resolve, reject) => {
		
		// 如果是单条 SQL，转换为数组
		const sqlArray = typeof sql === 'string' ? [sql] : sql;

		plus.sqlite.executeSql({
			name: dbName,
			sql: sqlArray,
			success: () => {
				resolve(true);
			},
			fail: (error: any) => {
				console.error(`sql执行失败,sql=${sql}`, error)
				resolve(false);
			}
		});
	});
}

/**
 * 查询语句
 * @param {string} dbName 数据库名
 * @param {string} sql 
 * @return 
 */ 
export function selectSql(dbName : string, sql : string) : Promise<any[]> {
	return new Promise((resolve, reject) => {
		plus.sqlite.selectSql({
			name: dbName,
			sql: sql,
			success: (data) => {
				resolve(data);
			},
			fail: (error) => {
				console.error(`查询sql执行失败,sql=${sql}`, error)
				reject(error);
			}
		});
	});
}